/**
 * 完成ls -r功能；利用对文件操作；
 * @author: sundx
 * @date: 2020-05-30 22:02:46
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-30 22:03:17
 */
#include <dirent.h>
#include <errno.h>
#include <iostream>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
void isFile(const char *);
void isFileDir(const char *);

int main(int argc, char *argv[]) {
  if (argc == 1) {
    isFile("..");
  } else {
    while (--argc) {
      isFile(*(++argv));
    }
  }
}

void isFile(const char *fileName) {
  int ret = 0;
  struct stat fileInfo; // 改动
  ret = stat(fileName, &fileInfo);
  if (ret == -1) {
    std::cout << "get the " << fileName << " status failed " << strerror(errno)
              << std::endl;
    exit(EXIT_FAILURE);
  }
  if (S_ISDIR(fileInfo.st_mode)) {
    isFileDir(fileName);
  }
  std::cout << fileName << "               " << fileInfo.st_size << std::endl;
}
void isFileDir(const char *fileName) {
  DIR *origin;
  dirent *dirDetail;
  int ret;
  // std::vector<char *> subFile;
  origin = opendir(fileName);
  if (origin == NULL) {
    std::cout << "opendir failed " << std::endl;
    exit(EXIT_FAILURE);
  }
  while ((dirDetail = readdir(origin)) != NULL) {
    if ((strcmp(dirDetail->d_name, ".") == 0) ||
        (strcmp(dirDetail->d_name, "..") == 0)) {
      continue;
    }
    // std::cout << dirDetail->d_name << std::endl;
    // subFile.push_back(dirDetail->d_name);
    char result[1024] = {'\0'};
    // 拼接字符串
    sprintf(result, "%s/%s", fileName, dirDetail->d_name);
    isFile(result);
  }
  ret = closedir(origin);
  if (ret == -1) {
    std::cout << "closedir error" << std::endl;
    exit(EXIT_FAILURE);
  }
  // for (auto i : subFile) {
  //   char result[1024] = {'\0'};
  //   sprintf(result, "%s/%s", fileName, i);
  //   isFile(result);
  // }
}